package cn.com.api.controller;

import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.redenvelope.RedEnvelope;
import cn.com.redenvelope.RedEnvelopeCreateListener;
import cn.com.redenvelope.RedEnvelopeCreateResult;
import cn.com.redenvelope.RedEnvelopeCreator;
import cn.com.redenvelope.RedEnvelopeSnatcher;
import cn.com.redenvelope.RedEnvelopeSnatchListener;
import cn.com.redenvelope.SnatchResult;
import cn.com.redenvelope.redis.RedisRedEnvelopeCreator;
import cn.com.redenvelope.redis.RedisRedEnvelopeSnatcher;
import cn.com.redis.RedisDistributionConnectionTool;
import cn.com.util.JsonUtil;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;

@Controller
@RequestMapping("api/redis/")
public class RedisTestorController {

	@RequestMapping(value = "testDSetkey")
	public void testRedis(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		RedisDistributionConnectionTool redisTool = new RedisDistributionConnectionTool();
		
		ShardedJedis client = redisTool.getRedisClient();
		Collection<JedisShardInfo> s = client.getAllShardInfo();
		Iterator<JedisShardInfo> it = s.iterator();
		for ( ; it.hasNext(); ) {
			JedisShardInfo in = it.next();
			//map.put(s.iterator().next().getHost(), s.iterator().next().getHost());
			System.out.println(in.getHost());
			System.out.println(in.getPassword());
			System.out.println(in.getName());
			System.out.println(in.getPort());
			//in.
		}
		client.del("*");
		
		try {
			String key = null;
			
			for (int i=0; i<1000; i++) {
				
				//client = redisTool.getRedisClient();
				
				key = String.valueOf(new java.util.Random().nextInt(10000));
						
				client.set(key, String.valueOf(new java.util.Random().nextInt(9999)));
				
				
			}
			
			client = redisTool.getRedisClient();
			redisTool.returnClientResource();
			map.put(key, client.get(key));
		} catch (Exception ex) {
			ex.printStackTrace();
			
			redisTool.returnBrokenClientResource();
		}
		
		
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
		
	}
	
	@RequestMapping(value = "testCreateRedEnvelope")
	public void testCreateRedEnvelope(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		
		RedEnvelopeCreator creator = new RedisRedEnvelopeCreator(3600 * 24);
		
		int envelopeId = 1;
		
		RedEnvelopeCreateResult rs = creator.createEnvelope(envelopeId, 1000, 20, 1, new RedEnvelopeCreateListener(){
			//闭包方法，用来判断当前红包是否可以创建，一般实际生产环境是根据数据库里的红包状态来判断
			//比如红包设为四种状态：未发起，已发起，已取消，已完成，显然只有未发起的红包可以继续执行
			@Override
			public boolean beforeCreateEnvelope() {
				return true;
			}

			@Override
			public boolean afterCreateEnvelope() {
				return true;
			}
		});
		
		if (rs == RedEnvelopeCreateResult.CREATE_SUCCESS) {
			map.put("result", "创建红包成功");
		} else if (rs == RedEnvelopeCreateResult.CREATE_FAILURE) {
			map.put("result", "创建红包失败");
		} else if (rs == RedEnvelopeCreateResult.COMPLETED) {
			map.put("result", "红包已经创建过，并且已经全部抢完毕");
		} else if (rs == RedEnvelopeCreateResult.HAS_CREATED) {
			map.put("result", "红包已经创建过");
		}
		
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	@RequestMapping(value = "testSnatchRedEnvelope")
	public void testSnatchRedEnvelope(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		for (int i=0; i<50; i++) {
			new Runnable() {
				public void run() {
					Map<String, Object> map = new HashMap<String, Object>();
					
					RedEnvelopeSnatcher snatcher = new RedisRedEnvelopeSnatcher();
					
					int envelopeId = 1;
					int memberId = new Random().nextInt(50);
					
					SnatchResult rs = snatcher.initSnatcher(envelopeId, memberId);
					
					if (rs == SnatchResult.SUCCESS) {
						if (snatcher.hasMoreEnvelope()) {
							snatcher.snatch(new RedEnvelopeSnatchListener() {

								@Override
								public void onEnvelopeComplete(RedEnvelope redEnvelope) {
									// TODO Auto-generated method stub
									
								}

								@Override
								public void onEnvelopeInvalid(RedEnvelope redEnvelope) {
									// TODO Auto-generated method stub
									
								}

								@Override
								public void onSnatchSuccess(RedEnvelope redEnvelope) {
									// TODO Auto-generated method stub
									
								}
								
							});
							map.put("result", "抢红包成功");
						} else {
							map.put("result", "没有更多红包了");
						}
					} else if (rs == SnatchResult.ENVELOPE_NOT_AVAILABLE) {
						map.put("result", "红包不存在");
					} else if (rs == SnatchResult.MEMBER_HAS_SNATCHED) {
						map.put("result", "该会员已经抢过红包");
					} else if (rs == SnatchResult.FAILURE) {
						map.put("result", "抢红包失败");
					} else if (rs == SnatchResult.ENVELOPE_COMPLETE) {
						map.put("result", "红包已抢光");
					} 
					
					System.out.println(JsonUtil.object2json(map));
				}
			}.run();
		}
		
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("result", "ok");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}
}
